﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MyWindowsService.Entity;
using MyWindowsService.Tools;
using Newtonsoft.Json;

namespace MyWindowsService
{
    public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }

        string filePath = $@"C:\ServiceLog{DateTime.Now:yyyy-MM-dd}.txt";

        private SqlService sqlService = new SqlService();
        private static int start = 1;
        private static int end = 100;

        protected override void OnStart(string[] args)
        {
            WriteFile($"{DateTime.Now},服务启动！");

            // 推送主页面数据
            MyTimer();

        }

        /// <summary>
        /// 推送主页面数据
        /// </summary>
        private void SendMainData()
        {
            //MyTimer();
            var ws = WebSocketHelper.GetInstance();
            var str = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss};运行了一次；";

            while (true)
            {
                var msgs = sqlService.GetMessages(start, end);

                //数据取完后从头再取一次
                if (!msgs.Any() && start > 1)
                {
                    start = 1;
                    end = 100;
                    msgs = sqlService.GetMessages(start, end);
                }

                //如果没有数据,发送空信息
                if (!msgs.Any())
                {
                    ws.SendMsg(new BaseViewModel { Mark = "/5KHS-Main", Message = "本次没有内容" }, 0);
                    ws.SendMsg(new BaseViewModel { Mark = "/5KHS-Check", Message = "本次没有内容" }, 0);
                    Thread.Sleep(1000);//停顿一秒
                }

                foreach (var hsParam in msgs)
                {
                    var viewModel = new MainViewModel { Message = "本消息为主页面" };

                    #region 生产进度

                    viewModel.ProgressView = new ProductionProgressViewModel
                    {
                        BrandName = hsParam.BrandBatch,
                        DayYield = $"{hsParam.TotalToday:F0}kg",
                        MonthYield = $"{hsParam.TotalMonth:F0}kg",
                        FinishedWeight = $"{hsParam.TotalDo:F0}",
                        NoFinishedWeight = $"{(hsParam.TotalPlan - hsParam.TotalDo):F0}"
                    };

                    #endregion

                    #region 设备参数

                    viewModel.ShebeiItems.Add(new MainItem { Name = "罩压力", Value = hsParam.K5_HS_SB_JK_001.ToString("F1") });
                    viewModel.ShebeiItems.Add(new MainItem { Name = "蒸汽压力", Value = hsParam.K5_HS_SB_JK_002.ToString("F1") });

                    #endregion

                    #region 考核指标

                    viewModel.KaoheItems.Add(new MainItem { Name = "出口烟丝水分均值", Value = hsParam.K5_HS_KH_JK_001.ToString("F1"), Unit = "%" });
                    viewModel.KaoheItems.Add(new MainItem { Name = "出口烟丝水分标偏", Value = hsParam.K5_HS_KH_JK_002.ToString("F1"), Unit = "" });
                    viewModel.KaoheItems.Add(new MainItem { Name = "热风温度均值", Value = hsParam.K5_HS_KH_JK_003.ToString("F1"), Unit = "℃" });
                    viewModel.KaoheItems.Add(new MainItem { Name = "热风温度标偏", Value = hsParam.K5_HS_KH_JK_004.ToString("F1"), Unit = "" });
                    viewModel.KaoheItems.Add(new MainItem { Name = "1区筒壁温度平均值", Value = hsParam.K5_HS_KH_JK_005.ToString("F1"), Unit = "℃" });
                    viewModel.KaoheItems.Add(new MainItem { Name = "2区筒壁温度平均值", Value = hsParam.K5_HS_KH_JK_006.ToString("F1"), Unit = "℃" });

                    #endregion

                    #region 工艺参数

                    viewModel.GongyiItems.Add(new MainItem { Name = "入口烟丝流量-实际值", Value = $"{hsParam.K5_HS_GY_JK_001:F0}kg/h" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "入口烟丝流量-设定值", Value = $"{hsParam.K5_HS_GY_JK_002:F0}kg/h" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "入口烟丝流量-累计值", Value = $"{hsParam.K5_HS_GY_JK_003:F0}kg" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "入口烟丝水分", Value = $"{hsParam.K5_HS_GY_JK_004:F1}%" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "出口烟丝水分-实际值", Value = $"{hsParam.K5_HS_GY_JK_005:F1}%" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "出口烟丝水分-设定值", Value = $"{hsParam.K5_HS_GY_JK_006:F1}%" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "1区筒壁温度-实际值", Value = $"{hsParam.K5_HS_GY_JK_007:F1}℃", Unit = "A1" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "2区筒壁温度-实际值", Value = $"{hsParam.K5_HS_GY_JK_008:F1}℃", Unit = "A2" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "滚筒风门开度", Value = $"{hsParam.K5_HS_GY_JK_009:F1}%" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "滚筒转速", Value = $"{hsParam.K5_HS_GY_JK_010:F0}r/min" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "热风速度-实际值", Value = $"{hsParam.K5_HS_GY_JK_011:F1}m/s" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "热风温度", Value = $"{hsParam.K5_HS_GY_JK_012:F1}℃" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "入口水分仪通道号", Value = $"{hsParam.K5_HS_GY_JK_013:F0}" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "出口水分仪通道号", Value = $"{hsParam.K5_HS_GY_JK_014:F0}" });
                    viewModel.GongyiItems.Add(new MainItem { Name = "SIROX蒸汽流量", Value = $"{hsParam.K5_HS_GY_JK_015:F1}kg/h" });

                    #endregion

                    #region 其他参数

                    viewModel.QitaItems.Add(new MainItem { Name = "脱水量", Value = $"{hsParam.K5_HS_QT_JK_001:F0}kg" });
                    viewModel.QitaItems.Add(new MainItem { Name = "脱水速度", Value = $"{hsParam.K5_HS_QT_JK_002:F0}" });
                    viewModel.QitaItems.Add(new MainItem { Name = "回潮加水量", Value = $"{hsParam.K5_HS_QT_JK_003:F0}kg" });
                    viewModel.QitaItems.Add(new MainItem { Name = "回潮出口水分", Value = $"{hsParam.K5_HS_QT_JK_004:F1}%" });
                    viewModel.QitaItems.Add(new MainItem { Name = "加料出口水分", Value = $"{hsParam.K5_HS_QT_JK_005:F1}%" });
                    viewModel.QitaItems.Add(new MainItem { Name = "1区冷凝水温度", Value = $"{hsParam.K5_HS_QT_JK_006:F1}℃" });
                    viewModel.QitaItems.Add(new MainItem { Name = "2区冷凝水温度", Value = $"{hsParam.K5_HS_QT_JK_007:F1}℃" });

                    #endregion

                    viewModel.Mark = "/5KHS-Main";
                    ws.SendMsg(viewModel);

                    WriteFile(str);
                    WriteFile(JsonConvert.SerializeObject(viewModel));

                    //推送生产前检查
                    var v = new BeforeCheckModel { Mark = "/5KHS-Check", Message = "本消息为生产前检查" };
                    v.Items.Add(new BeforeCheckConfigItem
                    {
                        KeyCode = "K5_HS_SB_NY_001",
                        Title = "水压力",
                        ShebeiMaxValue = "16",
                        StandardMaxValue = 7,
                        StandardMinValue = 5,
                        Unit = "bar",
                        Value = $"{hsParam.K5_HS_SB_NY_001:F1}"
                    });

                    v.Items.Add(new BeforeCheckConfigItem
                    {
                        KeyCode = "K5_HS_SB_NY_002",
                        Title = "电压",
                        ShebeiMaxValue = "420",
                        StandardMaxValue = 407,
                        StandardMinValue = 353,
                        Unit = "V",
                        Value = $"{hsParam.K5_HS_SB_NY_002:F1}"
                    });

                    v.Items.Add(new BeforeCheckConfigItem
                    {
                        KeyCode = "K5_HS_SB_NY_003",
                        Title = "压缩空气",
                        ShebeiMaxValue = "10",
                        StandardMaxValue = 6,
                        StandardMinValue = 4,
                        Unit = "bar",
                        Value = $"{hsParam.K5_HS_SB_NY_003:F1}"
                    });

                    v.Items.Add(new BeforeCheckConfigItem
                    {
                        KeyCode = "K5_HS_SB_NY_004",
                        Title = "蒸汽压力",
                        ShebeiMaxValue = "16",
                        StandardMaxValue = 3,
                        StandardMinValue = 1,
                        Unit = "bar",
                        Value = $"{hsParam.K5_HS_SB_NY_004:F1}"
                    });
                    ws.SendMsg(v);

                    Thread.Sleep(1000);//停顿一秒
                }

                start = end + 1;
                end = end + 100;
            }

        }

        protected override void OnStop()
        {
            WriteFile($"{DateTime.Now},服务停止！");
        }

        //实例化System.Timers.Timer   
        private void MyTimer()
        {
            System.Timers.Timer MT = new System.Timers.Timer(10000);
            MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent);
            MT.Enabled = true;
            MT.AutoReset = false;//只执行一次

        }

        //构造System.Timers.Timer实例   间隔时间事件   
        private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            SendMainData();
        }

        /// <summary>
        /// 写入到文件
        /// </summary>
        private void WriteFile(string str)
        {
            //using (FileStream stream = new FileStream(filePath, FileMode.Append))
            //using (StreamWriter writer = new StreamWriter(stream))
            //{
            //    writer.WriteLine(str);

            //}
        }
    }
}
